<?php
header('Content-Type: text/html;charset=utf-8');
header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 设置允许自定义请求头的字段
if( $_SERVER['REQUEST_METHOD'] == 'OPTIONS' ){
    exit('ok');
}

require_once  __DIR__.'/_init.php';

$a = $_SERVER['REQUEST_URI'];
$uri = rtrim(preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']), '/');
$params = explode('/', trim($uri, '/'));
$count = count($params);
if ($count > 1) {
    $controller = $params[0];
    $method = $params[1];
} elseif ($count == 1) {
    $controller = 'index';
    $method = $params[0];
} else {

}
//$func = "\\RedEnvelopes\\Modules\\" . $controller;
// 加载所有文件
foreach(glob(ST_ROOT . '/Modules/*')  as $php_file)
{
    require_once $php_file;
}
$filename = ST_ROOT .'/Modules/'.$controller.'.class.php';

# 文件不存在
if(!file_exists($filename)){
    echo json_encode(array(
       'state' => 404,
       'msgid' => 404,
    ));
    //$filename.' not find';
    return false;
}

$controller = 'controller_' . $controller;
$newObj = new $controller($method, $params);

#方法不存在
if(!method_exists($newObj,$method)){
    //echo '未定义'.$method.'方法！';
    echo json_encode(array(
        'state' => 404,
        'msgid' => 301,
    ));
    return false;
}
call_user_func_array(array($newObj, $method), $params);
//call_user_func_array($newObj, array($method, $args));